#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Time    : 2025/9/29 22:31
# @Author  : WXY
# @File    : CookiesHelper
# @PROJECT_NAME: youtubedown_gui
# @PRODUCT_NAME: PyCharm
# -------------------------------------------------------------------------------

import sys
import os
import base64
from PySide6.QtWidgets import QMainWindow
from PySide6.QtCore import Qt
from py_gui.cookieshelper_ui import Ui_cookiesHelper
from LoggerManager import logger_manager
from utils import SCROLLBARSTYLE, setup_window_icon


class CookiesHelperWindow(QMainWindow):
    """Cookies设置帮助窗口"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_cookiesHelper()
        self.ui.setupUi(self)
        
        # 设置窗口属性
        self.setup_window()
        
        # 设置样式
        self.setup_styles()
        
        # 设置内容
        self.setup_content()
        
        logger_manager.info("🍪 Cookies帮助窗口已初始化", "CookiesHelper")
    
    def setup_window(self):
        """设置窗口属性"""
        try:
            # 设置窗口标题
            self.setWindowTitle("Cookies设置帮助")
            self.ui.lbl_title.setText("🍪 Cookies设置详细帮助")
            # 设置窗口图标
            setup_window_icon(self)
            
            # 设置最小窗口大小
            self.setMinimumSize(600, 400)
            
            # 设置为非模态窗口
            self.setWindowModality(Qt.WindowModality.NonModal)
            
            # 设置窗口标志，允许最小化、最大化和关闭
            self.setWindowFlags(Qt.WindowType.Window | 
                              Qt.WindowType.WindowMinimizeButtonHint | 
                              Qt.WindowType.WindowMaximizeButtonHint | 
                              Qt.WindowType.WindowCloseButtonHint)
            
            logger_manager.info("✅ 窗口属性设置完成", "CookiesHelper")
            
        except Exception as e:
            logger_manager.error(f"设置窗口属性失败: {e}", "CookiesHelper")
    
    def setup_styles(self):
        """设置样式"""
        try:
            # QTextBrowser样式设置
            # text_browser_style = """
            # QTextBrowser {
            #     background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
            #         stop:0 rgba(15,15,35,0.95),
            #         stop:1 rgba(26,26,46,0.95));
            #     border: 2px solid rgba(255,255,255,0.1);
            #     border-radius: 12px;
            #     color: white;
            #     font-family: 'Microsoft YaHei', 'SimHei', 'Arial', sans-serif;
            #     font-size: 14px;
            #     padding: 15px;
            #     selection-background-color: rgba(76,175,80,0.3);
            #     line-height: 1.8;
            # }
            # QTextBrowser:focus {
            #     border: 2px solid rgba(76,175,80,0.6);
            #     background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
            #         stop:0 rgba(15,15,35,1.0),
            #         stop:1 rgba(26,26,46,1.0));
            # }
            # """

            # 应用样式
           # self.ui.txt_content.setStyleSheet(text_browser_style + SCROLLBARSTYLE)
            self.ui.txt_content.setStyleSheet( SCROLLBARSTYLE)
            logger_manager.info("✅ 样式设置完成", "CookiesHelper")
            
        except Exception as e:
            logger_manager.error(f"设置样式失败: {e}", "CookiesHelper")

    def get_image_base64(self, image_path):
        """将图片转换为base64格式，兼容打包环境"""
        try:
            # 获取正确的图片路径
            if getattr(sys, 'frozen', False):
                # 打包环境：从 _MEIPASS 获取
                full_path = os.path.join(sys._MEIPASS, 'imgs', image_path)
            else:
                # 开发环境：相对于当前文件的路径
                current_dir = os.path.dirname(os.path.abspath(__file__))
                full_path = os.path.join(os.path.dirname(current_dir), 'imgs', image_path)
            
            if os.path.exists(full_path):
                with open(full_path, "rb") as img_file:
                    img_data = img_file.read()
                    img_base64 = base64.b64encode(img_data).decode('utf-8')
                    return f"data:image/png;base64,{img_base64}"
            else:
                logger_manager.warning(f"图片文件不存在: {full_path}", "CookiesHelper")
                return ""
        except Exception as e:
            logger_manager.error(f"转换图片为base64失败: {e}", "CookiesHelper")
            return ""

    def setup_content(self):
        """设置帮助内容"""
        try:
            # 获取图片的base64编码
            excookies_image = self.get_image_base64("excookies.png")
            export_image = self.get_image_base64("export.png")
            savecookies_image = self.get_image_base64("savecookies.png")
            coffee_image_base64 = self.get_image_base64("custom_coffee.jpg")
            help_content = f"""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <style>
                    body {{
                        font-family: 'Microsoft YaHei', 'SimHei', 'Arial', sans-serif;
                        background: transparent;
                        color: #ffffff;
                        margin: 0;
                        padding: 20px;
                        line-height: 1.8;
                    }}
                    .title-primary {{
                        color: #4CAF50;
                        font-size: 24px;
                        font-weight: bold;
                        margin-bottom: 15px;
                        text-align: center;
                        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
                    }}
                    .title-secondary {{
                        color: #2196F3;
                        font-size: 20px;
                        font-weight: bold;
                        margin-top: 25px;
                        margin-bottom: 15px;
                        border-left: 4px solid #2196F3;
                        padding-left: 15px;
                    }}
                    .title-info {{
                        color: #FF9800;
                        font-size: 20px;
                        font-weight: bold;
                        margin-top: 25px;
                        margin-bottom: 15px;
                        border-left: 4px solid #FF9800;
                        padding-left: 15px;
                    }}
                    .divider-primary {{
                        border: none;
                        height: 3px;
                        background: linear-gradient(90deg, #4CAF50, #81C784, #4CAF50);
                        margin: 20px 0;
                        border-radius: 2px;
                    }}
                    .divider-secondary {{
                        border: none;
                        height: 2px;
                        background: linear-gradient(90deg, #2196F3, #64B5F6, #2196F3);
                        margin: 20px 0;
                        border-radius: 1px;
                    }}
                    .divider-info {{
                        border: none;
                        height: 2px;
                        background: linear-gradient(90deg, #FF9800, #FFB74D, #FF9800);
                        margin: 20px 0;
                        border-radius: 1px;
                    }}
                    .paragraph {{
                        margin-bottom: 15px;
                        text-indent: 2em;
                        font-size: 16px;
                        color: #E0E0E0;
                    }}
                    .ordered-list {{
                        margin-left: 20px;
                        margin-bottom: 20px;
                    }}
                    .list-item {{
                        margin-bottom: 8px;
                        font-size: 16px;
                        color: #E0E0E0;
                        line-height: 1.6;
                    }}
                    .link {{
                        color: #4CAF50;
                        text-decoration: none;
                        font-weight: bold;
                        transition: color 0.3s ease;
                    }}
                    .link:hover {{
                        color: #81C784;
                        text-decoration: underline;
                    }}
                    .highlight-blue {{
                        background: linear-gradient(45deg, #FFD700, #FFA500);
                        color: #38a6dc;
                        padding: 2px 6px;
                        border-radius: 4px;
                        font-weight: bold;
                        box-shadow: 0 2px 4px rgba(255,215,0,0.3);
                    }}
                    .highlight-green {{
                        background: linear-gradient(45deg, #4CAF50, #81C784);
                        color: #fff;
                        padding: 2px 6px;
                        border-radius: 4px;
                        font-weight: bold;
                        box-shadow: 0 2px 4px rgba(76,175,80,0.3);
                    }}
                    .highlight-orange {{
                        background: linear-gradient(45deg, #FF9800, #FFB74D);
                        color: #fff;
                        padding: 2px 6px;
                        border-radius: 4px;
                        font-weight: bold;
                        box-shadow: 0 2px 4px rgba(255,152,0,0.3);
                    }}
                    .image-container {{
                       text-align: center;
                        margin: 5px 0 0 0;
                        padding: 8px;
                        background: rgba(255,255,255,0.05);
                        border-radius: 8px;
                        border: 1px solid rgba(255,255,255,0.1);
                    }}
                    .image {{
                        max-width: 85%;
                        height: auto;
                        border-radius: 8px;
                        transition: transform 0.3s ease;
                        display: block;
                        margin: 0 auto;
                    }}
                    .image:hover {{
                        transform: scale(1.02);
                    }}
                    .code-block {{
                        background: rgba(0,0,0,0.4);
                        border: 1px solid rgba(255,255,255,0.2);
                        border-radius: 8px;
                        padding: 15px;
                        margin: 15px 0;
                        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
                        overflow-x: auto;
                    }}
                    .code {{
                        color: #A5D6A7;
                        font-size: 14px;
                        line-height: 1.5;
                    }}
                    .info-box {{
                        border-radius: 8px;
                        padding: 20px;
                        margin: 20px 0;
                        border-left: 5px solid;
                    }}
                    .info-box-info {{
                        background: rgba(33,150,243,0.1);
                        border-left-color: #2196F3;
                    }}
                     
                    .info-box-success {{
                        background: rgba(76,175,80,0.1);
                        border-left-color: #4CAF50;
                    }}
                    .qa-item {{
                        margin-bottom: 3px;
                    }}
                    .question {{
                        color: #FFB74D;
                        font-weight: bold;
                    }}
                    .answer {{
                        color: #E0E0E0;
                        margin-left: 20px;
                    }}
                </style>
            </head>
            <body>
                
                <p class="paragraph">这里使用Edge浏览器作为演示, 首先要安装<span class="highlight-blue">Get cookies.txt LOCALLY</span>扩展, 必须是这个扩展, 其他的扩展我也测试过, yt_dlp支持的并不好</p>
                <ol class="ordered-list">
                    <li class="list-item">打开Chrome/Edge浏览器，访问 <a href="https://chromewebstore.google.com/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc?pli=1" class="link">Chrome扩展商店</a><br>
                    扩展下载地址: https://chromewebstore.google.com/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc?pli=1</li>"""
            
            # 添加第一张图片
            if excookies_image:
                help_content += f"""
                     <div class="image-container">
                        <img src="{excookies_image}" alt="扩展安装" class="image"  > </div>
                   """
            else:
                help_content += """
                    <div class="image-container">
                        <p style="color: #ff6b6b;">📷 扩展安装图片加载失败</p>
                    </div>"""
            
            help_content += """
                    <li class="list-item">使用 Edge浏览器 访问 <a href="https://www.youtube.com/" class="link">https://www.youtube.com/</a>, 并登录您的YouTube账户</li>
                    <li class="list-item">登录之后, 打开<span class="highlight-blue">Get cookies.txt LOCALLY</span>扩展, 然后点击<span class="highlight-green">Export</span></li>"""
            
            # 添加第二张图片
            if export_image:
                help_content += f"""
                    <div class="image-container">
                        <img src="{export_image}" alt="导出Cookies" class="image">
                    </div>"""
            else:
                help_content += """
                    <div class="image-container">
                        <p style="color: #ff6b6b;">📷 导出Cookies图片加载失败</p>
                    </div>"""
            
            help_content += """
                    <li class="list-item">这个时候在你的下载目录会有一个<span class="highlight-orange">www.youtube.com_cookies.txt</span></li>
                    <li class="list-item">打开<span class="highlight-orange">www.youtube.com_cookies.txt</span>, 全选里面的全部内容, 然后粘贴到 <span class="highlight-green">本项目的Cookies设置</span> 的文本框里面</li>
                    <li class="list-item">点击<span class="highlight-green">保存Cookies</span>即可</li>"""
            
            # 添加第三张图片
            if savecookies_image:
                help_content += f"""
                                        <div class="image-container">
                        <img src="{savecookies_image}" alt="保存Cookies" class="image">
                    </div>"""
            else:
                help_content += """
                                        <div class="image-container">
                        <p style="color: #ff6b6b;">📷 保存Cookies图片加载失败</p>
                    </div>"""
            
            help_content += """
                </ol>
                <hr class="divider-secondary">
                <h2 class="title-secondary">📝 Cookies格式说明</h2>
                <p class="paragraph">本项目使用的Cookies格式, 示例如下：</p>
                <div class="code-block">
                    <code class="code">
                        # Netscape HTTP Cookie File<br>
                        .youtube.com&nbsp;&nbsp;&nbsp;&nbsp;TRUE&nbsp;&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;&nbsp;FALSE&nbsp;&nbsp;&nbsp;&nbsp;1234567890&nbsp;&nbsp;&nbsp;&nbsp;session_token&nbsp;&nbsp;&nbsp;&nbsp;abc123<br>
                        .youtube.com&nbsp;&nbsp;&nbsp;&nbsp;TRUE&nbsp;&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;&nbsp;FALSE&nbsp;&nbsp;&nbsp;&nbsp;1234567890&nbsp;&nbsp;&nbsp;&nbsp;VISITOR_INFO1_LIVE&nbsp;&nbsp;&nbsp;&nbsp;xyz789
                    </code>
                </div>
                
                <hr class="divider-info">
                <h2 class="title-info">🔍 常见问题解答</h2>
                <div class="info-box info-box-info">
                    <div class="qa-item">
                        <p class="question">Q: 为什么需要cookies？</p>
                        <p class="answer">A: 某些YouTube视频需要登录才能访问，cookies可以模拟登录状态。</p>
                    </div>
                    <div class="qa-item">
                        <p class="question">Q: cookies会过期吗？</p>
                        <p class="answer">A: 是的，YouTube的cookies通常会在一段时间后过期，需要重新获取。</p>
                    </div>
                    <div class="qa-item">
                        <p class="question">Q: 获取cookies安全吗？</p>
                        <p class="answer">A: 本地获取cookies是相对安全的，但请不要将cookies分享给他人。</p>
                    </div>
                </div>
                 
                
                <div class="info-box info-box-success">
                    <div class="qa-item">
                        <p class="question">✅ 如有帮助, 请打赏：</p>"""

            # 只有当图片存在时才添加图片标签
            if coffee_image_base64:
                help_content += f"""
                <p style="margin-bottom:0px ;margin:0; padding:0;"><img src="{coffee_image_base64}" alt="Coffee" 
                width="500" height="300" style="display: block; margin: 0 auto;vertical-align:middle;"></p>"""
            else:
                help_content += """
                <p style="text-align: center; color: #ff6b6b;">☕ 图片加载失败！</p>"""

            help_content += """
                    </div>
                </div>
            </body>
            </html>
            """
            
            # 设置HTML内容
            self.ui.txt_content.setHtml(help_content)
            
            # 启用外部链接
            self.ui.txt_content.setOpenExternalLinks(True)
            
            logger_manager.info("✅ 帮助内容设置完成", "CookiesHelper")
            
        except Exception as e:
            logger_manager.error(f"设置帮助内容失败: {e}", "CookiesHelper")
    def closeEvent(self, event):
        """窗口关闭事件"""
        try:
            logger_manager.info("🍪 Cookies帮助窗口正在关闭", "CookiesHelper")
            event.accept()
        except Exception as e:
            logger_manager.error(f"关闭Cookies帮助窗口时发生错误: {e}", "CookiesHelper")
            event.accept()